/**
 * 
 */
package wpmp.security.client.internal;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import wcommons.httputils.HttpUtils;
import wcommons.httputils.quickbean.RespInfo;
import wcommons.lang.quickbean.Entry;
import wpmp.security.client.SecurityConfig;
import wpmp.utils.quickbean.User;
import wpmp.utils.quickbean.UserPermission;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 1:58:08 PM Dec 4, 2013
 */
public class PmpUserUtils {

	private static final Log log = LogFactory.getLog(PmpUserUtils.class);

	private static final String GET_USER = "user.do?action=get";

	// 用户数据不会很多的
	private static final Map<String, Entry<User, Long>> CACHE = new HashMap<String, Entry<User, Long>>();

	private static final long TIMEOUT = 1 * 60 * 60 * 1000;// 缓存失效时间为1小时

	public static void init() {

	}

	/**
	 * 根据用户名获取用户
	 * 
	 * @param loginName
	 * @return
	 */
	public static User getByLoginName(String loginName) {
		// 先从缓存中获取
		final Entry<User, Long> entry = CACHE.get(loginName);
		// 未失效则直接使用
		if (entry != null && (System.currentTimeMillis() - entry.getValue() < TIMEOUT)) {
			return entry.getKey();
		}

		// 从服务端获取
		final Map<String, Object> params = new HashMap<String, Object>();
		params.put("loginName", loginName);
		final String result = HttpUtils.postForString(SecurityConfig.getAuthUrl(GET_USER), params);
		if (StringUtils.isBlank(result)) {
			return null;
		}
		try {
			final RespInfo<User> respInfo = JSON.parseObject(result, new TypeReference<RespInfo<User>>() {
			});
			if (!respInfo.isSuccess()) {
				log.warn("Failed to getUser by loginName[" + loginName + "], AuthServer response " + respInfo);
				return null;
			}
			final User user = respInfo.getResult();
			// 缓存
			CACHE.put(user.getLoginName(), new Entry<User, Long>(user, System.currentTimeMillis()));
			return user;
		}
		catch (Exception e) {
			// ignore
			log.warn("Error to getUser by loginName[" + loginName + "] from AuthServer\r\n", e);
			return null;
		}
	}

	/**
	 * 根据当前登录用户
	 * 
	 * @param securityId
	 * @return
	 */
	public static User get(HttpServletRequest req) {
		final UserPermission userPermission = PmpResourceUtils.getAndSetUserPermission(req);
		if (userPermission != null) {
			return userPermission.getUser();
		}
		return null;
	}
}
